package com.hjm.mall.config.handler;

import com.fasterxml.jackson.databind.ObjectMapper;
import lombok.SneakyThrows;
import org.apache.ibatis.type.BaseTypeHandler;
import org.apache.ibatis.type.JdbcType;

import java.sql.CallableStatement;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;

/**
 * 将json转为String[]
 */
public class JsonStringArrayTypeHandler extends BaseTypeHandler<String[]> {

    private static final ObjectMapper objectMapper = new ObjectMapper();

    @SneakyThrows
    @Override
    public void setNonNullParameter(PreparedStatement ps, int i, String[] parameter, JdbcType jdbcType) throws SQLException {
        // 将String[]转换为JSON字符串并设置到PreparedStatement中
        String json = objectMapper.writeValueAsString(parameter);
        ps.setString(i, json);
    }

    @Override
    public String[] getNullableResult(ResultSet rs, String columnName) throws SQLException {
        String json = rs.getString(columnName);
        if (json == null) {
            return null;
        }
        try {
            // 从JSON字符串中解析String[]
            return objectMapper.readValue(json, String[].class);
        } catch (Exception e) {
            throw new SQLException("Error parsing JSON to String array", e);
        }
    }

    @Override
    public String[] getNullableResult(ResultSet rs, int columnIndex) throws SQLException {
        return getNullableResult(rs, rs.getMetaData().getColumnName(columnIndex));
    }

    @Override
    public String[] getNullableResult(CallableStatement cs, int columnIndex) throws SQLException {
        return getNullableResult(cs.getResultSet(), columnIndex);
    }
}
